package com.shop.service.impl;

import com.shop.dao.UserMapper;
import com.shop.dao.UserTokenMapper;
import com.shop.entity.User;
import com.shop.entity.UserToken;
import com.shop.service.UserService;
import com.shop.util.Hash;
import com.shop.util.NumberUtil;
import com.shop.util.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserTokenMapper userTokenMapper;

    String reg = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";

    @Override
    public String login(String username, String password) {
        User user = userMapper.selectByUserName(username);

        //如果user不为空，并且密码正确
        if (user != null && Hash.compare(password, user.getPassword())) {
            String token = getNewToken(System.currentTimeMillis() + "", user.getUserId());
            UserToken userToken = userTokenMapper.selectByPrimaryKey(user.getUserId());
            //当前时间
            Date now = new Date();
            //过期时间
            Date expireTime = new Date(now.getTime() + 7 * 24 * 3600 * 1000);//过期时间 48 小时
            if (userToken == null) {
                userToken = new UserToken();
                userToken.setUserId(user.getUserId());
                userToken.setToken(token);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                //新增一条token数据
                if (userTokenMapper.insertSelective(userToken) > 0) {
                    //新增成功后返回
                    return token;
                }
            } else {
                userToken.setToken(token);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                //更新
                if (userTokenMapper.updateByPrimaryKeySelective(userToken) > 0) {
                    //修改成功后返回

                    return token;
                }
            }
        }
        return "50001";//用户名或密码错误
    }

    @Override
    public int register(String username, String password) {

        if (!password.matches(reg)) {
            return 50002;//密码必须包含字母和数字，且在6~18位之间
        }

        if (userMapper.selectByUserName(username) != null) {
            return 50004;//用户名已存在
        }
        User registerUser = new User();
        registerUser.setUsername(username);
        registerUser.setPassword(Hash.hash(password));
        if (userMapper.insert(registerUser) > 0) {
            return 20000;
        }
        return 500;//数据库爆炸
    }

    @Override
    public Boolean logout(Long userId) {
        return userTokenMapper.deleteByPrimaryKey(userId) > 0;
    }


    @Override
    public Boolean updatePassword(Long userId, String originalPassword, String newPassword) {
        User user = userMapper.selectByUserId(userId);
        //当前用户非空才可以进行更改
        if (user != null) {
            //比较原密码是否正确
            if (Hash.compare(originalPassword, user.getPassword())) {
                if (!newPassword.matches(reg)) {
                    return false;//密码必须包含字母和数字，且在6~18位之间
                }
                //设置新密码并修改
                user.setPassword(Hash.hash(newPassword));
                if (userMapper.updateUser(user) > 0 && userTokenMapper.deleteByPrimaryKey(userId) > 0) {
                    //修改成功且清空当前token则返回true
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public int toSeller(User user) {
        user.setUserType(1);
        if (userMapper.updateUser(user) > 0) {
            return 20000;
        }
        return 50009;
    }


    /**
     * 获取token值
     *
     * @param timeStr
     * @param userId
     * @return
     */
    private String getNewToken(String timeStr, Long userId) {
        String src = timeStr + userId + NumberUtil.genRandomNum(6);
        return SystemUtil.genToken(src);
    }
}
